package com.chao.base.io.fileio;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author : Rookie
 * @description : 异步IO是指在进行IO操作时，程序不会等待IO操作完成，而是继续执行下一步操作，
 * * 当IO操作完成后，系统会通知程序进行相应的处理。
 * * 在Java中，异步IO主要是通过AsynchronousChannel和CompletionHandler来实现的。
 * @date : 2023/6/13
 */
public class AioDemo {

    public static void main(String[] args) {
        read();
        write();
    }

    private static void read() {
        AsynchronousFileChannel fileChannel = null;
        InputStream is = AioDemo.class.getClassLoader().getResourceAsStream("test.txt");
        if (is != null) {
            try {
                Path path = Files.createTempFile("temp", null);
                Files.copy(is,path);
                // 开启通道
                fileChannel = AsynchronousFileChannel.open(path);
                // 创建缓冲区
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                // 异步读取到缓冲区
                Future<Integer> future = fileChannel.read(buffer, 0);
                future.get();

                buffer.flip();
                String content = StandardCharsets.UTF_8.decode(buffer).toString();
                System.out.println(content);
            } catch (IOException | InterruptedException | ExecutionException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (fileChannel != null) {
                        fileChannel.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void write() {
        AsynchronousFileChannel fileChannel = null;
        Path path = Paths.get("aioTest.txt");
        try {
            fileChannel = AsynchronousFileChannel.open(path);
            ByteBuffer buffer = ByteBuffer.wrap("hello,aio".getBytes(StandardCharsets.UTF_8));
            Future<Integer> future = fileChannel.write(buffer, 0);
            future.get();

        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
